package service.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import service.edu.entity.Chapter;
import service.edu.entity.Video;
import service.edu.entity.chapter.ChapterVo;
import service.edu.entity.chapter.SectionVo;
import service.edu.exception.CustomException;
import service.edu.mapper.ChapterMapper;
import service.edu.service.ChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import service.edu.service.VideoService;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author diao
 * @since 2020-08-05
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {
    @Autowired
    private VideoService videoService;//注入小节

    //树形形式显示章节与小节
    @Override
    public List<ChapterVo> getAllChapters(String courseId) {
        QueryWrapper<Chapter> chapterWrapper = new QueryWrapper<>();
        chapterWrapper.eq("course_id", courseId);
        List<Chapter> chapterList = baseMapper.selectList(chapterWrapper);//根据课程id获取所有章节
        QueryWrapper<Video> videoWrapper = new QueryWrapper<>();
        videoWrapper.eq("course_id", courseId);
        List<Video> videoList = videoService.list(videoWrapper);//根据课程id获取所有小节

        //构建chapter与section的vo列表
        List<ChapterVo> chapterVoList = new ArrayList<>();
        List<SectionVo> sectionVoList=new ArrayList<>();
        for (Chapter chapter : chapterList) {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapter,chapterVo);
            for (Video video : videoList) {
                SectionVo sectionVo = new SectionVo();
                if (video.getChapterId().equals(chapter.getId())){
                    BeanUtils.copyProperties(video, sectionVo);
                    sectionVoList.add(sectionVo);
                  }
            }
            //对chapterVo对象添加小节列表
            chapterVo.setChildren(sectionVoList);
            //向章节列表添加章节对象
            chapterVoList.add(chapterVo);
        }
        //返回章节列表
        return chapterVoList;
    }

    //当章节没有小节内容时才能删除章节
    @Override
    public boolean deleteChapterById(String chapterId) {
        QueryWrapper<Video> videoQueryWrapper = new QueryWrapper<>();
        videoQueryWrapper.eq("chapter_id", chapterId);
        List<Video> videoList = videoService.list(videoQueryWrapper);
        int length = videoList.size();
        if (length==0){
            int i = baseMapper.deleteById(chapterId);
            return i>0;//大于0即返回true，否则为false
        }else {
            System.out.println("章节内含有小节,不能删除!");
            throw  new CustomException(666,"不能删除!");
        }
    }
}
